package com.lebang.medicalInquiry.utils;


import com.alibaba.fastjson.JSONObject;
import com.aliyun.live20161101.Client;
import com.aliyun.live20161101.models.DescribeLiveStreamsOnlineListRequest;
import com.aliyun.live20161101.models.DescribeLiveStreamsOnlineListResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.Common;
import darabonba.core.exception.TeaException;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ResponseBody;

import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AuthLiveUrlUtil {


    /**
     * 计算md5
     *
     * @param param
     * @return
     */
    public static String md5(String param) {
        if (param == null || param.length() == 0) {
            return null;
        }
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(param.getBytes());
            byte[] byteArray = md5.digest();

            BigInteger bigInt = new BigInteger(1, byteArray);
            // 参数16表示16进制
            String result = bigInt.toString(16);
            // 不足32位高位补零
            while (result.length() < 32) {
                result = "0" + result;
            }
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 生成推流地址
     *
     * @param pushDomain 推流域名
     * @param pushKey    推流域名配置的鉴权Key
     * @param appName    推流AppName
     * @param streamName 推流StreamName
     * @param expireTime 过期时间（单位是秒）
     */
    public static String generate_push_url(String pushDomain, String pushKey, String appName, String streamName, long expireTime) {
        String pushUrl = "";
        //推流域名未开启鉴权功能的情况下
        if (pushKey == "") {
            return "rtmp://" + pushDomain + "/" + appName + "/" + streamName;
        } else {
            long timeStamp = System.currentTimeMillis() / 1000L + expireTime;
            String stringToMd5 = "/" + appName + "/" + streamName + "-" + Long.toString(timeStamp) + "-0-0-" + pushKey;
            String authKey = md5(stringToMd5);
            return "rtmp://" + pushDomain + "/" + appName + "/" + streamName + "?auth_key=" + Long.toString(timeStamp) + "-0-0-" + authKey;
        }

    }

    /**
     * 生成播放地址
     *
     * @param pullDomain 播放域名
     * @param pullKey    播放鉴权Key
     * @param appName    播放appName（同推流appName)
     * @param streamName 播放streamName，播放源流时，streamName 同推流streamName；播放转码流时，streamName 为推流streamName_{转码模板ID}
     * @param expireTime 过期时间（单位是秒）
     */
    public static String general_pull_url(String pullDomain, String pullKey, String appName, String streamName, long expireTime) {
        String rtmpUrl = ""; //rtmp的拉流地址
        String hlsUrl = ""; //m3u8的拉流地址
        String flvUrl = ""; //flv的拉流地址
        //播放域名未配置鉴权Key的情况下
        if (pullKey == "") {
            return "rtmp://" + pullDomain + "/" + appName + "/" + streamName;
//            hlsUrl = "http://"+pullDomain+"/"+appName+"/"+streamName+".m3u8";
//            flvUrl = "http://"+pullDomain+"/"+appName+"/"+streamName+".flv";
        } else {
            long timeStamp = System.currentTimeMillis() / 1000L + expireTime;
//            String rtmpToMd5 = "/"+appName+"/"+streamName+"-"+Long.toString(timeStamp)+"-0-0-"+pullKey;
//            String rtmpAuthKey = md5(rtmpToMd5);
//            return  "rtmp://"+pullDomain+"/"+appName+"/"+streamName+"?auth_key="+Long.toString(timeStamp)+"-0-0-"+rtmpAuthKey;

//            String hlsToMd5 = "/"+appName+"/"+streamName+".m3u8-"+Long.toString(timeStamp)+"-0-0-"+pullKey;
//            String hlsAuthKey = md5(hlsToMd5);
//            hlsUrl = "http://"+pullDomain+"/"+appName+"/"+streamName+".m3u8"+"?auth_key="+Long.toString(timeStamp)+"-0-0-"+hlsAuthKey;
//
            String flvToMd5 = "/" + appName + "/" + streamName + ".flv-" + Long.toString(timeStamp) + "-0-0-" + pullKey;
            String flvAuthKey = md5(flvToMd5);
            return flvUrl = "http://" + pullDomain + "/" + appName + "/" + streamName + ".flv" + "?auth_key=" + Long.toString(timeStamp) + "-0-0-" + flvAuthKey;
        }
//        System.out.println("RTMP播放地址为： "+rtmpUrl);
//        System.out.println("m3u8播放地址为： "+hlsUrl);
//        System.out.println("flv播放地址为： "+flvUrl);
    }

    //    public static com.aliyun.live20161101.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
//        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
//                // 必填，您的 AccessKey ID
//                .setAccessKeyId(accessKeyId)
//                // 必填，您的 AccessKey Secret
//                .setAccessKeySecret(accessKeySecret);
//        // Endpoint 请参考 https://api.aliyun.com/product/live
//        config.endpoint = "live.aliyuncs.com";
//        return new com.aliyun.live20161101.Client(config);
//    }
    public static com.aliyun.live20161101.Client Initialization(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret).setRegionId("cn-shenzhen");

        return new com.aliyun.live20161101.Client(config);
    }

    public static boolean getOnLineStreamStatus(String accessKeyId, String accessKeySecret, String domainName, String appName, String streamName) {

        // Endpoint 请参考 https://api.aliyun.com/product/live
        com.aliyun.live20161101.Client client = null;
        try {
            client = Initialization(accessKeyId, accessKeySecret);

            DescribeLiveStreamsOnlineListRequest request = new DescribeLiveStreamsOnlineListRequest()
                    .setDomainName(domainName)
                    .setAppName(appName)
                    .setStreamName(streamName)
                    .setQueryType("strict");
            DescribeLiveStreamsOnlineListResponse response = client.describeLiveStreamsOnlineList(request);
            final String s = Common.toJSONString(Common.toMap(response));
            final JSONObject resultJson = JSONObject.parseObject(s);
            final Integer statusCode = resultJson.getInteger("statusCode");
            if (200 == statusCode) {
                final Integer totalNum = resultJson.getJSONObject("body").getInteger("TotalNum");
//                System.out.println("流活跃列表获取:"+resultJson.toJSONString());
                if (totalNum > 0) {
                    return true;
                }
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;

    }


//    public static void main(String[] args_) throws Exception {
//        java.util.List<String> args = java.util.Arrays.asList(args_);
//        try {
//            String domainName = args.get(0);
//            String appName = args.get(1);
//            String streamName = args.get(2);
//            Integer pageSize = com.aliyun.darabonbanumber.Client.parseInt(args.get(3));
//            Integer pageNum = com.aliyun.darabonbanumber.Client.parseInt(args.get(4));
//            String streamType = args.get(5);
//            String queryType = args.get(6);
//            String regionId = args.get(7);
//            com.aliyun.live20161101.Client client = Sample.Initialization(regionId);
//            DescribeLiveStreamsOnlineListResponse response = Sample.DescribeLiveStreamsOnlineListSample(client, domainName, appName, streamName, pageSize, pageNum, streamType, queryType);
//            com.aliyun.teaconsole.Client.log(com.aliyun.teautil.Common.toJSONString(com.aliyun.teautil.Common.toMap(response)));
//        } catch (TeaException error) {
//            com.aliyun.teaconsole.Client.log(error.message);
//        } catch (Exception _error) {
//            TeaException error = new TeaException(_error.getMessage(), _error);
//            com.aliyun.teaconsole.Client.log(error.message);
//        }
//    }


    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //生成长度为5的随机字符串作为appName和streamName（字母和数字组合）
        String appName = "live";
        ;
        String streamName = "1234";
        ;

        long expireTime = 3600L;
        String pullDomain = "pullstream.digitalmate.cn";
        String pullKey = "TC7B1meJN95766nq";

        String pushDomain = "pushstream.digitalmate.cn";
        String pushKey = "1VV78bIp5aKPh1Qm";
        final String s = general_pull_url(pullDomain, pullKey, appName, streamName, expireTime);
        final String s1 = generate_push_url(pushDomain, pushKey, appName, streamName, expireTime);
        System.out.println(s);
        System.out.println(s1);
    }
}
